//index.js

import Dialog from '@vant/weapp/dialog/dialog';

const netUtils = require('./../../util/netUtils.js');
var CryptoJS = require('./../../util/util.js');
var config = require('../../config.js')
var util = require('../../util/util.js');
import Notify from '@vant/weapp/notify/notify';

const app = getApp()
Page({
  data: {
    avatarUrl: './user-unlogin.png',
    userInfo: {},
    date:"",
    phone: "",
    logged: false,
    takeSession: false,
    requestResult: '',
    show_title_txt: true,
    title_txt: '小艾云锁开发中...敬请期待！',
    background: ['http://smartlifee.com/wechatxiaozhi/image/image1.png', 'http://smartlifee.com/wechatxiaozhi/image/image2.png', 'http://smartlifee.com/wechatxiaozhi/image/image3.png'],
    indicatorDots: true,
    vertical: false,
    autoplay: false,
    interval: 2000,
    duration: 500,
    author_show: false,
    author_phone_show: false,
    dev_list: [],
    devicesids: [],
    showMsgpopup: false,
    netWorkType:"",
    setInter:""
  },
  // dev_list: ['0', '1', '3']
  onOpenSeting() {
    console.log('onOpenSeting')
    wx.openSetting({
      success(res) {
        // console.log(res.authSetting)
        if (!res.authSetting['scope.userInfo']) {
          wx.authorize({
            scope: 'scope.userInfo',
            success() {
              console.log('userInfo')
              // 必须是在用户已经授权的情况下调用
              wx.getUserInfo({
                success: function(res) {
                  var userInfo = res.userInfo
                  var nickName = userInfo.nickName
                  var avatarUrl = userInfo.avatarUrl
                  var gender = userInfo.gender //性别 0：未知、1：男、2：女
                  var province = userInfo.province
                  var city = userInfo.city
                  var country = userInfo.country
                  // console.log('userInfo:', userInfo)
                  // console.log('nickName:', nickName)
                  // console.log('avatarUrl:', avatarUrl)
                  // console.log('gender:', gender)
                  // console.log('province:', province)
                  // console.log('city:', city)
                  // console.log('country:', country)
                }
              })
            }
          })
        } else {
          wx.getUserInfo({
            success: function(res) {
              var userInfo = res.userInfo
              console.log('userInfo2:', userInfo)
            }
          })
        }
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              console.log('userLocation')
            }
          })
        }
      }
    })
  },
  getUserInfo(event) {
    console.log(event.detail);
  },
  getPhoneNumber(e) {
    console.log(e.detail.errMsg)
    console.log(e.detail.iv)
    console.log(e.detail.encryptedData)
    var _this = this
    this.setData
    wx.login({
      success(res) {
        if (res.code) {
          //发起网络请求
          console.log(res.code)
          wx.request({
            url: config.url.getPhoneNumber,
            method: 'POST',
            data: {
              'encryptedData': e.detail.encryptedData,
              'iv': e.detail.iv,
              'code': res.code,
              'client': config.client,
              'id': 2,
            },
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            success(res) {
              // console.log(res.data)
              try {
                wx.setStorageSync('phone', res.data.phoneNumber)
              } catch (e) {}
              config.phone = res.data.phoneNumber
              _this.setData({
                  phone: res.data.phoneNumber
                }
              )
            },
            fail(err) {
              console.err(err)
            }

          })
        } else {
          console.log('登录失败！' + res.errMsg)
          this.setData({
            author_show: true
          });
        }
      }
    })
  },

  onUserInfoClose() {
    this.setData({
      author_show: false
    });
  },

  onClickTitle(e) {
    console.log(e)
  },
  // equipment_details
  to_devmessage(e) {
    // console.log('to_devmessage', e)

    wx.navigateTo({
      url: '../devmessage/devmessage?uuid=' + e.currentTarget.dataset.value.fields.uuid + "&host_user=" + e.currentTarget.dataset.value.fields.host_user + "&phone=" + this.data.phone,
    })
  },
  to_adddev() {
    var _this = this
    try {
      var userinfo = wx.getStorageSync('userinfo')
      var phone = wx.getStorageSync('phone')

      console.log("userinfo:", userinfo)
      console.log("phone:", phone)

      if ((userinfo == '') || (phone == '') || (typeof userinfo == 'undefined') || (typeof phone == 'undefined')) {
        // wx.redirectTo({
        //   url: '../login/login?id=1',
        // })
        Dialog.confirm({
          title: '提醒',
          message: '添加设备需要访问您的手机号，是否同意我们的隐私协议',
        })
          .then(() => {
            // on confirm
             wx.redirectTo({
               url: '../login/login?id=1',
            })
          })
          .catch(() => {
            // on cancel
          });

      } else {
        config.phone = phone
        wx.navigateTo({
          url: '../adddev/adddev?phone='+this.data.phone,
        })
     //   console.log('有进来=>',)
        // _this.setData({
        //   showAddPoup: true
        // })
      }
      _this.setData({
        phone: phone
      })
    } catch (e) {
      // Do something when catch error
    }
  },
  // wifi添加
  navigateToWifi() {
    var _this = this
    // 拿取token
    wx.request({
      url: config.url.getClientToken,
      method: 'POST',
      data: {
        appid: config.appid,
        client: config.client,
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success(res) {
        console.log(res.data)
        if (res.data.code == "200") {
          _this.setData({
            token: '' + res.data.data
          })
          try {
            wx.setStorageSync('token', res.data.data)
          } catch (e) {}
          _this.startWifi()
        } else {
          
          wx.showToast({
            title: '获取用户ID失败',
            icon: 'none',
            duration: 2000
          })
        }
      },
    })
  },
  // 二维码添加
  navigateToScan() {
    var _this = this
    wx.scanCode({
      success(res) {
        // console.log("typeof", typeof (res))
        console.log('ssss', res)
        // console.log(JSON.stringify(res.result))
        if (res.errMsg == "scanCode:ok") {
          var dd = res.result
          var search = "https://www.apai.vip/wechat/miniprogram/?id=";
          var str0 = dd.substr(search.length)
          //  console.log('str0:', str0)

          var str = CryptoJS.Decrypt(str0);

          var json = JSON.parse(str)
          var code = json.code
          console.log('code:', code)

          var uuid = json.uuid
          console.log('uuid:', uuid)

          var mainphone = json.phone
          console.log('mainphone:', mainphone)

          var timestamp = json.timestamp
          console.log('timestamp:', timestamp)
          var hTime = parseInt(timestamp)
          var qTime = new Date().getTime()
          console.log('后时间', hTime, '前时间', qTime, '时间', qTime - hTime)

          if (code != '200') {
            wx.showToast({
              title: '无效二维码，请用本产品分享的二维码',
              icon: 'none',
              duration: 2000
            })
          } else if (qTime - hTime > 6 * 60 * 1000) {
            wx.showToast({
              title: '无效二维码，请获取新的二维码',
              icon: 'none',
              duration: 2000
            })
          } else {
            //添加设备到服务器
            wx.request({
              url: config.url.addOthderDev,
              method: 'POST',
              dataType: "json",
              data: {
                uuid: uuid,
                phone: _this.data.phone,
                mainphone: mainphone,
                client: config.client,
              },
              header: {
                // 'content-type': 'application/json', // 默认值
                "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
              },
              success(res) {
                console.log(res.data)
                console.log("code:", res.data.code)

                if (res.data.code == 200) {
                  wx.showToast({
                    title: '添加成功',
                    icon: 'succeed',
                    duration: 2000
                  })
                } else if (res.data.code == 201) {
                  wx.showToast({
                    title: '主设备不存在',
                    icon: 'none',
                    duration: 2000
                  })
                } else if (res.data.code == 202) {
                  wx.showToast({
                    title: '主用户不存在',
                    icon: 'none',
                    duration: 2000
                  })
                } else if (res.data.code == 203) {
                  wx.showToast({
                    title: '用户未注册，请先登录',
                    icon: 'none',
                    duration: 2000
                  })
                } else if (res.data.code == 204) {
                  wx.showToast({
                    title: '同一设备不能反复添加',
                    icon: 'none',
                    duration: 2000
                  })
                } else if (res.data.code == 205) {
                  wx.showToast({
                    title: '设备已经存在',
                    icon: 'none',
                    duration: 2000
                  })
                } else {
                  wx.showToast({
                    title: '添加失败，请检查二维码',
                    icon: 'none',
                    duration: 2000
                  })

                }

              },
              fail(e) {
                console.error(e)

              }
            })
          }

        } else {
          wx.showToast({
            title: '请重新扫一扫',
            icon: 'none',
            duration: 2000
          })
        }

        //JSON.parse(jsonstr); //可以将json字符串转换成json对象
        // JSON.stringify(jsonobj); //可以将json对象转换成json对符串
      }
    })
  },
  startWifi(callback = function () {}) {
    var _this = this
    console.log('ssss1111')
    wx.startWifi({
      success(res) {
        console.log('ssss',res.errMsg)
        if (res.errMsg == "startWifi:ok") {
          wx.getConnectedWifi({
            success: function (e) {
              console.log("wifi e:", e)
              if (e.errMsg == "getConnectedWifi:ok") {
                var str = e.wifi.SSID
                console.log("indexOf:", str.indexOf('AP-'), 'length:', str.length)
                if ((str.indexOf('AP-') == 0) && (str.length == 18)) {
                  wx.showToast({
                    title: '请先连接正常上网的WIFI',
                    icon: 'none',
                    duration: 2000
                  })
                } else {
                  wx.navigateTo({
                    url: '../ap_wifi_config/ap_wifi_config?token=' + _this.data.token,
                  })
                }
              }
            },
            fail: function (e) {
              console.log("wifi err:", e)
              if (e.errCode == 12005) {
                wx.showToast({
                  title: '请先连接正常上网的WIFI',
                  icon: 'none',
                  duration: 2000
                })
              } else if (e.errCode == 12006) {
                wx.showToast({
                  title: '请先打开GPS定位',
                  icon: 'none',
                  duration: 2000
                })
              }
            }

          })
        }
      },
      fail (rej) {
        console.log('什么', rej)
      }
    })
  },
  changeIndicatorDots() {
    this.setData({
      indicatorDots: !this.data.indicatorDots
    })
  },

  changeAutoplay() {
    this.setData({
      autoplay: !this.data.autoplay
    })
  },

  intervalChange(e) {
    this.setData({
      interval: e.detail.value
    })
  },

  durationChange(e) {
    this.setData({
      duration: e.detail.value
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log("onLoad")
    var _this = this

 //   console.log("0 index onload" + JSON.stringify(options))
    app.globalData.bootStatus = false

    try {
      var userinfo = wx.getStorageSync('userinfo')
      var phone = wx.getStorageSync('phone')
  
      console.log("userinfo:", userinfo)
      console.log("phone:", phone)
  
      if ((phone == '') || (typeof phone == 'undefined')) {
        // Remove the Dialog.confirm call
        config.phone = ''
      } else {
        config.phone = phone
      }
      _this.setData({
        phone: phone
      })
    } catch (e) {
      // Do something when catch error
    }

    //在此函数中获取扫描普通链接二维码参数
    let q = decodeURIComponent(options.q)
    console.log("qr" , q)
    if (q != 'undefined') {
      
      // var search = "https://www.apai.vip/wechat/miniprogram/?id=";
      var search = config.url.shareQrdata;
      console.log("search=", search, "length:", search.length)
      var str0 = q.substr(search.length)
      console.log('str0:', str0)
      //  console.log("index 生命周期 onload 参数 flag=" + utils.getQueryString(q, 'flag'))

      if (str0.length >20)
      {
        var str = CryptoJS.Decrypt(str0);

        var json = JSON.parse(str)
        var code = json.code
        console.log('code:', code)

        var uuid = json.uuid
        console.log('uuid:', uuid)

        var mainphone = json.phone
        console.log('mainphone:', mainphone)

        var timestamp = json.timestamp
        console.log('timestamp:', timestamp)
        var hTime = parseInt(timestamp)
        var qTime = new Date().getTime()
        // console.log('后时间', hTime, '前时间', qTime, '时间', qTime - hTime)

        if (qTime - hTime < 6 * 60 * 1000) {
          wx.request({
            url: config.url.addOthderDev,
            method: 'POST',
            dataType: "json",
            data: {
              uuid: uuid,
              phone: _this.data.phone,
              mainphone: mainphone,
              client: config.client,
            },
            header: {
              // 'content-type': 'application/json', // 默认值
              "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
            },
            success(res) {
              console.log(res.data)
              console.log("code:", res.data.code)

              if (res.data.code == 200) {
                wx.showToast({
                  title: '添加成功',
                  icon: 'succeed',
                  duration: 2000
                })
              }
              else {
                wx.showToast({
                  title: '添加失败，无效二维码',
                  icon: 'none',
                  duration: 2000
                })

              }

            },
            fail(e) {
              console.error(e)

            }
          })
        }
      }
     
      
     
    }
    console.log("login phone", _this.data.phone)
    if (_this.data.phone != "")
    {
      //login
      wx.login({
        success(res) {
          if (res.code) {
            //发起网络请求
            console.log("login:", res.code)
            wx.request({
              url: config.url.Login,
              method: 'POST',
              data: {
                'code': res.code,
                'phone': _this.data.phone,
                'client': config.client,

              },
              header: {
                "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
              },
              success(res) {
                console.log(res)
              },
              fail(err) {
                console.err(err)
              }

            })
          } else {
            console.log('登录失败！' + res.errMsg)
          }
        }
      })
    }
  

    wx.getSetting({
      withSubscriptions: true,
      success(res) {
        // console.log("authSetting", res.authSetting)
        if (!res.authSetting['scope.userInfo']) {
          console.log("userInfo1")
          wx.authorize({
            scope: 'scope.userInfo',
            success() {
              console.log('userInfo2')
              // 必须是在用户已经授权的情况下调用
              wx.getUserInfo({
                success: function(res) {
                  var userInfo = res.userInfo
                  console.log('userInfo:', userInfo)

                }
              })
            }
          })
        }
        console.log("subscriptionsSetting", res.subscriptionsSetting)
      }
    })

  },

  onShow () {
    // console.log("onShow", app.globalData.MQ)
    //console.log("bootStatus", app.globalData.bootStatus)
    console.log("MQConnectd", app.globalData.MQConnectd)
    
     var that = this
    // if (!app.globalData.bootStatus)
    // {
    //   if (!app.globalData.MQConnectd) {
    //     Notify({ type: 'warning', message: '服务器正在连接中...' });
    //   }
    // }
    // 调用函数时，传入new Date()参数，返回值是日期和时间
    var date = util.formatDate(new Date());
    console.log('date', date)
    console.log('phone', this.data.phone)

     

    // console.log('getNetworkType')
    // wx.getNetworkType({
    //   success: function (res) {
    //     console.log('getNetworkType', res)
    //     that.setData({
    //       netWorkType: res.networkType
    //     })
    //   }
    // })
    that.data.setInter = setInterval(function () {
      netUtils.judgeNetworkStatus(function (res) {
        //none 是无网络状态下，networkType 的值
        //console.log("time NetworkStatus:", app.globalData.netStatus, res)

        if ("none" != res) {
          //有网了，干你要干的事儿吧
          that.setData({
            netWorkType: res
          })
          if (app.globalData.netStatus == false) {
            console.log("index net ")
            wx.hideLoading()
            app.logoutConnect()
            app.AppGetDevList()
            //  app.initSocket()
            app.globalData.netStatus = true
            that.getDevList()
          }
         

        } else {
          // app.globalData.bootStatus = true
          app.globalData.netStatus = false
          console.log("net no")
          return;
        }
      })
    }, 5000) //延迟时间 这里是5秒

      netUtils.judgeNetworkStatus(function (res) {
      //none 是无网络状态下，networkType 的值
      console.log("index NetworkStatus:", app.globalData.netStatus,typeof(res),res)

      if ("none" != res) {
        //有网了，干你要干的事儿吧
        that.setData({
          netWorkType: res
        })
        if (app.globalData.netStatus== false)
        {
          console.log("index net ")
          wx.hideLoading()
          app.logoutConnect()
          app.AppGetDevList()
          //  app.initSocket()
           app.globalData.netStatus = true
          that.getDevList()
        }
        else
        {
          if ((typeof that.data.phone == 'undefined') || (that.data.phone == '')) {
          }
          else {
            that.getDevList()
          }
        }
       
      } else {
        // app.globalData.bootStatus = true
        app.globalData.netStatus =false
        console.log("net no")
        return;
      }
    })

 
   

    this.setData({
      showMsgpopup: true,
      date: date
    })
  
    
  },

  onHide () {
    console.log("onHide")
    clearInterval(this.data.setInter)
    this.setData({
      showMsgpopup: false
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  getDevList () {
    var _this = this
    console.log('getDevList')
    wx.request({
      url: config.url.getDevList,
      method: 'POST',
      data: {
        'phone': _this.data.phone,
        'client': config.client,
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
      },
      success(res) {
        console.log('res:',res)
        if (res.data.code == 200) {
          let result = res.data.data || []
          _this.setData({
            dev_list: result
          })
          // 订阅消息
          if (result.length >0)
          {
            let uuids = result.map(item => {
              return item.fields.uuid
            })

          let devicesids = result.map(item => {
            return item.fields.uuid.substring(8)
          })
          //console.log('设备devicesids=>',  devicesids)
          _this.setData({
            devicesids: devicesids
          })
          // console.log('设备id=>', res.data.data, uuids)
          app.globalData.uuids = uuids
          //config.mqtt.clientId = _this.data.phone
          // console.log('index clientId', config.mqtt.clientId)
          // if(!app.globalData.bootStatus)
          // {
          //   app.globalData.bootStatus = true
          //   app.initSocket()
          // }
          }
         
               
        }
        else if (res.data.code == 203)
        {
          try {
            wx.setStorageSync('phone', '')
          } catch (e) { }
          wx.redirectTo({
            url: '../login/login?id=1',
          })
        }
      },
      //fail(err) {
        // console.err(err)
     // }
    })
  },
  onReady: function() {
    console.log("onReady")
  },
  onUnload(){
    console.log("onUnload")
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    console.log("onShareAppMessage")
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: '小艾云锁',
      path: '/pages/index/index'
    }
  }
})